﻿using System;
using Utils;

namespace StockAnalyst2
{
	internal class DataBaseChecker
	{
		#region Attributes

		private readonly string _server;
		private readonly string _database;
		private readonly IDataBaseClient _dbClient;

		#endregion

		#region Public Methods

		public DataBaseChecker(string server, string database)
		{
			_server = server;
			_database = database;
			_dbClient = new SqlDataBaseClient(string.Format(Properties.Settings.Default.DatabaseLessConnectionString, _server));
		}

		public bool IsDataBaseServerAvailable()
		{
			try
			{
				_dbClient.ExecuteQuery("USE [master]");
				return true;
			}
			catch (Exception)
			{
				return false;
			}
		}

		public bool IsDataBaseAvailable()
		{
			try
			{
				_dbClient.ExecuteQuery(string.Format("USE [{0}]", _database));
				return true;
			}
			catch (Exception)
			{
				return false;
			}
		}

		public bool IsDataBaseStructureValid()
		{
			try
			{
				_dbClient.ExecuteQuery(string.Format("USE [{0}]; SELECT TOP 1 * FROM [ExchangeMarketHolidays]", _database));
				_dbClient.ExecuteQuery(string.Format("USE [{0}]; SELECT TOP 1 * FROM [ExchangeMarkets]", _database));
				_dbClient.ExecuteQuery(string.Format("USE [{0}]; SELECT TOP 1 * FROM [Notifications]", _database));
				_dbClient.ExecuteQuery(string.Format("USE [{0}]; SELECT TOP 1 * FROM [QuotationTables]", _database));
				_dbClient.ExecuteQuery(string.Format("USE [{0}]; SELECT TOP 1 * FROM [StockGroups]", _database));
				_dbClient.ExecuteQuery(string.Format("USE [{0}]; SELECT TOP 1 * FROM [StockGroups-Stocks]", _database));
				_dbClient.ExecuteQuery(string.Format("USE [{0}]; SELECT TOP 1 * FROM [Stocks]", _database));
				return true;
			}
			catch (Exception)
			{
				return false;
			}
		}

		#endregion
	}
}
